import { Component } from "react";
import TodoList from "./todolist/todolist.component";
import AddTodo from "./addtodo/addtodo.component";
import "./main.css";
import CategoryTab from "./ahotab/ahotab.component";

class TabPanel extends Component {
  render() {
    const { children, value, index, ...other } = this.props;
    return (
      <div
        role="tabpanel"
        hidden={value !== index}
        id={`tabpanel-${index}`}
        aria-labelledby={`tabpanel-${index}`}
        {...other}
      >
        {children}
      </div>
    );
  }
}

class App extends Component {
  constructor() {
    super();
    this.id = 4;
    this.state = {
      tab: "todo",
      items: [
        { id: 1, title: "a", isFinished: false },
        { id: 2, title: "abcd", isFinished: false },
        { id: 3, title: "12345", isFinished: false },
      ],
    };
  }

  onAddTodoHandler(e) {
    this.setState({
      items: [
        ...this.state.items,
        { id: this.id++, title: e, isFinished: false },
      ],
    });
  }
  handleChange = (event, newTab) => {
    this.setState({ tab: newTab });
  };
  onItemChangeHandler(id) {
    this.setState({
      items: this.state.items.map((item) => {
        if (item.id == id) {
          item.isFinished = !item.isFinished;
        }
        return item;
      }),
    });
  }
  handleItemDelete(id) {
    this.setState({
      items: this.state.items.filter((item) => {
        return !(item.id === id);
      }),
    });
  }
  render() {
    return (
      <div className="todoapp">
        <h2>AhoTODO</h2>
        <AddTodo onAddTodoHandler={this.onAddTodoHandler.bind(this)} />
        <CategoryTab onChange={this.handleChange.bind(this)} />
        <hr className="divider" color="grey" />
        <TabPanel value={this.state.tab} index="todo">
          <TodoList
            items={this.state.items.filter((item) => {
              return !item.isFinished;
            })}
            onItemChange={this.onItemChangeHandler.bind(this)}
            onItemDelete={this.handleItemDelete.bind(this)}
          />
        </TabPanel>
        <TabPanel value={this.state.tab} index="finished">
          <TodoList
            items={this.state.items.filter((item) => {
              return item.isFinished;
            })}
            onItemChange={this.onItemChangeHandler.bind(this)}
            onItemDelete={this.handleItemDelete.bind(this)}
          />
        </TabPanel>
      </div>
    );
  }
}
export default App;
